<template>
  <VTable ref="tableRef" v-bind="tableOptins">
    <template #form="{ form }">
      <XForm :fieldList="fieldList" :formOption="optionsData" :formData="form">
        <template #create_user="{ value, input }">
          <VCascader
            :model-value="value"
            @update:model-value="input"
            collapse-tags
            class="w-[200px]"
            placeholder="创建人"
          />
        </template>
      </XForm>
    </template>
    <template #toolbar_btns>
      <VActionBar :actions="actions" />
    </template>
    <template #exchange_rate="{ row }">
      <div>{{ row.currency }} {{ formatNumber(row.exchange_rate) }}</div>
    </template>
    <template #operate="{ row }">
      <el-button
        link
        type="primary"
        @click="handleApproval(row)"
        v-hasPermi="[financeManageAuthList.initial_bills.moreaudit]"
      >
        审核
      </el-button>
      <el-button
        link
        type="primary"
        @click="handleLog(row)"
        v-hasPermi="[financeManageAuthList.initial_bills.log]"
      >
        日志
      </el-button>
    </template>
  </VTable>
  <ConfirmInput
    title="审核"
    class="w-[500px]"
    confirmButtonText="确认"
    v-model="approvalVisible"
    :loading="loading"
    :field-options="approvalOptions"
    :rules="approvalRules"
    @submit="handleApprovalReq"
  />
  <Log
    dialog
    v-model="logVisible"
    :autoLoad="false"
    tag="finance.initial-bills"
    :business_id="logId"
    @close="logId = ''"
  />
  <AuditRuleDialog v-model="auditRuleVisible" @refresh="refresh" />
  <WarnDialog v-model="warnVisible" :optionsData="optionsData" />
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { financeManageAuthList } from "@/Auth/finance-manage.js";
import XForm from "@/components/XForm/index.vue";
import Log from "@/components/Log/index.vue";
import { config_name } from "@/config/export.js";
import { getTableSelectRow } from "@/hooks/tool.js";
import { tcBillDiff, auditSubmit } from "../../api/index";
import { formatNumber } from "@/utils/tool.js";
import ConfirmInput from "@/components/ConfirmInput/index.vue";
import AuditRuleDialog from "../AuditRuleDialog/index.vue";
import ApplyPayDialog from "../ApplyPayDialog/index.vue";
import DerivedCenter from "@/components/DerivedCenter/index.vue";
import WarnDialog from "../WarnDialog/index.vue";
import { tabName } from "../../data.js";
const router = useRouter();
const { proxy } = getCurrentInstance();

const props = defineProps({
  optionsData: { type: Object, default: () => {} },
  type: { type: String, default: "" },
});
const { optionsData } = toRefs(props);
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      dateRange: { type: "submit_time", value: [], range: false }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  rowConfig: {
    height: 75,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    {
      fixed: "left",
      title: "账单编号",
      width: 200,
      field: "bill_number",
      slots: {
        default: ({ row }) => {
          return (
            <el-link
              underline={false}
              type="primary"
              onClick={() => handleDetail(row.id)}
            >
              {row.bill_number}
            </el-link>
          );
        },
      },
    },
    {
      title: "账单名称",
      width: 200,
      field: "bill_name",
      slots: {
        default: ({ row }) => {
          return (
            <el-link
              underline={false}
              type="primary"
              onClick={() => handleLink(row?.bill_file?.oss_path)}
            >
              {row?.bill_name}
            </el-link>
          );
        },
      },
    },
    {
      title: "账单类型",
      width: 80,
      field: "bill_cycle_type_text",
    },
    { title: "物流商名称", width: 200, field: "logistics_name" },
    {
      title: "导入匹配信息",
      width: 200,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <span>
                导入<span class="text-[#3487FF]">{row.import_num || 0}</span>/
              </span>
              <span>
                成功<span class="text-[#3487FF]">{row.success_num || 0}</span>/
              </span>
              <span>
                警告<span class="text-[#3487FF]">{row.warning_num || 0}</span>/
              </span>
              <span>
                错误<span class="text-[#3487FF]">{row.error_num || 0}</span>
              </span>
            </div>
          );
        },
      },
    },
    // { title: "物流账单金额", width: 140, field: "logistics_amount" },
    // { title: "系统金额", width: 140, field: "system_amount" },
    // { title: "差异金额", width: 140, field: "difference_amount" },
    { title: "月账单金额/CNY", width: 160, field: "month_bill_amount_cny" },
    { title: "周账单金额/CNY", width: 160, field: "week_bill_amount_cny" },
    { title: "差异金额/CNY", width: 160, field: "diff_mw_bill_amount_cny" },
    {
      title: "币种汇率",
      width: 160,
      field: "exchange_rate",
      slots: { default: "exchange_rate" },
    },
    { title: "状态", width: 140, field: "audit_status_label" },
    { title: "申付金额", width: 160, field: "request_pay_amount" },
    { title: "付款金额", width: 160, field: "pay_amount" },
    {
      title: "人员",
      width: 400,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="flex">
                <div class="mr-[20px]  min-w-[80px]">
                  提交：{row.submit_user || "-"}
                </div>
                <div>审核：{row.audit_user || "-"}</div>
              </div>
              <div class="flex">
                <div class="mr-[20px] min-w-[80px]">
                  申付：{row.request_user || "-"}
                </div>
                <div>付款：{row.pay_user || "-"}</div>
              </div>
              <div>导入：{row?.import_user || "-"}</div>
            </div>
          );
        },
      },
    },
    {
      title: "时间",
      width: 420,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="flex">
                <div class="mr-[20px]  min-w-[180px]">
                  提交：{row.submit_time || "-"}
                </div>
                <div>审核：{row.audit_time || "-"}</div>
              </div>
              <div class="flex">
                <div class="mr-[20px] min-w-[180px]">
                  申付：{row.request_time || "-"}
                </div>
                <div>付款：{row.pay_time || "-"}</div>
              </div>
              <div>导入：{row?.import_time || "-"}</div>
            </div>
          );
        },
      },
    },
    { title: "物流备注", width: 200, field: "logistics_remark" },
    { title: "财务备注", width: 200, field: "finance_remark" },
    {
      title: "原始账单文件",
      width: 200,
      field: "original_bill",
      slots: {
        default: ({ row }) => {
          return (
            <el-button
              link
              type="primary"
              onClick={() => handleLink(row?.original_bill_file?.oss_path)}
            >
              {row?.original_bill_file?.original_bill_file}
            </el-button>
          );
        },
      },
    },
    {
      title: "操作",
      width: 120,
      fixed: "right",
      slots: { default: "operate" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        let obj = {
          ...form,
          _dtg:"FINANCE"
        };
        return tcBillDiff({ ...obj, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});

const handleDetail = (id) => {
  router.push(`/finance-manage/initial-bills/detail?id=${id}`);
};

const handleLink = (_link) => {
  if (!_link) return;
  window.open(_link, "noopener", "noreferrer");
};
const logId = ref("");
const logVisible = ref(false);
const handleLog = (item) => {
  logId.value = item.id;
  logVisible.value = true;
};

//审核
const approvalOptions = [
  {
    label: "审核",
    field: "audit",
    type: "radio",
    style: { width: "100%" },
    options: {
      data: [
        { label: "通过", value: "pass" },
        { label: "驳回", value: "rejected" },
      ],
    },
    itemProps: {
      popperAppendToBody: true,
      teleported: true,
    },
  },
  {
    label: "驳回原因",
    field: "remark",
    type: "textarea",
    autosize: { minRows: 4, maxRows: 8 },
    show: ({ model }) => model.audit === "rejected",
  },
];

const approvalRules = {
  audit: [{ required: true, message: "请选择审核状态", trigger: "blur" }],
};
const loading = ref(false);
const approvalVisible = ref(false);
const handleApproval = (row) => {
  approvalVisible.value = true;
  tableRef.value?.$table.setCheckboxRow(row, true);
};

const handleApprovalReq = async (formValues) => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const id = records.map((item) => item.id);
  try {
    loading.value = true;
    const { code, message, data } = await auditSubmit({
      id,
      ...formValues,
    });
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    if (data?.success_data?.length) {
      ElMessage.success({
        dangerouslyUseHTMLString: true,
        message: data.success_data.join("<br/>"),
      });
    }
    if (data?.fail_data?.length) {
      ElMessage.error({
        dangerouslyUseHTMLString: true,
        message: data.fail_data.join("<br/>"),
      });
    }
    approvalVisible.value = false;
    handleRefresh();
  } catch (e) {
  } finally {
    loading.value = false;
  }
};
const auditRuleVisible = ref(false);
const handleApprovalRule = () => {
  auditRuleVisible.value = true;
};

//导出中心
const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["finance_manage"]["initial_bill_audit"],
    condition,
  });
};

const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const warnVisible = ref(false);
const actions = ref([
  {
    label: "批量审核",
    type: "primary",
    fn: handleApproval,

    permission: [financeManageAuthList.initial_bills.moreaudit],
  },
  {
    label: "警告配置",
    fn: () => (warnVisible.value = true),

    permission: [financeManageAuthList.initial_bills.warnconfig],
  },
  {
    label: "审核规则配置",
    right: true,
    fn: handleApprovalRule,
    permission: [financeManageAuthList.initial_bills.auditruleconfig],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [financeManageAuthList.initial_bills.export],
  },
]);

const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "bill_number",
    placeholder: "账号编号",
    type: "input",
    ...publicStyle,
  },
  {
    field: "logistics_id",
    type: "select",
    options: {
      placeholder: "物流商名称",
      labelKey: "logistics_name",
      valueKey: "logistics_id",
    },
    collapseTags: true,
    multiple: true,
    class: "select-wrapper-style",
    originOption: "map.logistics",
  },
  {
    field: "reconcile_status",
    type: "select",
    originOption: "reconcile_status",
    options: {
      placeholder: "状态",
      data: [
        { label: "全部", value: "" },
        { label: "启用", value: 1 },
        { label: "禁用", value: 0 },
      ],
    },
    ...publicStyle,
  },
  {
    field: "time",
    type: "dateTimeRange",
    style: { width: "360px" },
    select: [
      { label: "提交时间", value: "submit_time" },
      { label: "审核时间", value: "audit_time" },
    ],
    itemProps: {
      startPlaceholder: "最早时间",
      endPlaceholder: "最晚时间",
    },
  },
];
</script>
<style lang="scss" scoped>
.vx-table {
  height: calc(100% - 80px) !important;
}
</style>
